package com.hnichr.ump.ecard.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hnichr.ump.common.ecard.entity.EcardBusinessCard;
import com.hnichr.ump.common.ecard.entity.EcardCompany;
import com.hnichr.ump.common.ecard.service.EcardBusinessCardService;
import com.hnichr.ump.common.ecard.vo.WxBindVO;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EcardBusinessCardServiceImpl extends BaseServiceImpl<EcardBusinessCard> implements EcardBusinessCardService {

    @Value("${wx.ecard.appid}")
    private String appId;

    @Value("${wx.ecard.appsecret}")
    private String appSecret;

    //default avatar
    //private static final String DEFAULT_AVATAR = "https://res.hn-talent.com/hn-talent-ump/2022/10/25/27c3ec30-e25a-4e45-ab3c-49194fcf0a2b.jpg";

    @Override
    @Transactional(readOnly = true)
    public EcardBusinessCard getByOpenId(String openId){
        List<EcardBusinessCard> cardList = JpaUtil.linq(EcardBusinessCard.class).equal("openId",openId).equal("status","1").list();
        if(CollectionUtils.isNotEmpty(cardList)){
            EcardBusinessCard card = cardList.get(0);

            if(StringUtils.isBlank(card.getHiddenAvatar())){
                card.setHiddenAvatar("1");
            }
            else if(StringUtils.isBlank(card.getAvatarUrl())){
                card.setHiddenAvatar("1");
            }
            return card;
        }
        return null;
    }

    @Override
    @Transactional(readOnly = false)
    public String bind(WxBindVO vo){
        if(StringUtils.isBlank(vo.getIdCardNo())||StringUtils.isBlank(vo.getNickName())||StringUtils.isBlank(vo.getOpenId())){
            return "参数不合法";
        }

        List<EcardBusinessCard> existsOpenList = JpaUtil.linq(EcardBusinessCard.class).equal("openId",vo.getOpenId()).equal("status","1").list();
        if(CollectionUtils.isNotEmpty(existsOpenList)){
            return "用户已绑定";
        }

        List<EcardBusinessCard> cardList = JpaUtil.linq(EcardBusinessCard.class).or().equal("idCardNo",StringUtils.lowerCase(vo.getIdCardNo())).equal("idCardNo",StringUtils.upperCase(vo.getIdCardNo())).end().equal("nickName",vo.getNickName()).equal("status","1").list();
        if(CollectionUtils.isNotEmpty(cardList)){
            if(cardList.size()>1){
                return "数据异常";
            }
            EcardBusinessCard businessCard = cardList.get(0);
            businessCard.setOpenId(vo.getOpenId());
            this.update(businessCard);
            return null;
        }
        return "身份证或姓名输入错误";
    }


    @Override
    @Transactional(readOnly = true)
    public String getOpenIdByCode(String code){
        String wxUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        String url = String.format(wxUrl,appId,appSecret,code);
        String resultJson = HttpUtil.get(url);
        JSONObject jsonObject = JSON.parseObject(resultJson);
        if(jsonObject.containsKey("openid")){
            return (String)jsonObject.get("openid");
        }
        return null;
    }

    @Override
    @Transactional
    public EcardBusinessCard update(EcardBusinessCard c){
        EcardBusinessCard card = this.getById(EcardBusinessCard.class,c.getId());
        card.setNickName(c.getNickName());
        card.setJob(c.getJob());
        card.setDepartment(c.getDepartment());
        card.setEmail(c.getEmail());
        card.setMobile(c.getMobile());
        card.setPhone(c.getPhone());
        card.setStatus(c.getStatus());
        card.setIdCardNo(c.getIdCardNo());
        card.setCompanyId(c.getCompanyId());
        card.setAvatarUrl(c.getAvatarUrl());
        card.setHiddenAvatar(c.getHiddenAvatar());
        super.update(card);
        return c;
    }

    @Override
    @Transactional
    public List<EcardBusinessCard> list(Criteria c){
        List<EcardBusinessCard> cardList = this.list(EcardBusinessCard.class,c);
        if(CollectionUtils.isEmpty(cardList)){
            return cardList;
        }
        Map<String,String> companyMap = getCompanyMap();
        for(EcardBusinessCard card:cardList){
            card.setCompanyName(companyMap.get(card.getCompanyId()));
        }
        return cardList;
    }

    @Override
    @Transactional
    public Page<EcardBusinessCard> listPage(Pageable page, Criteria c){
        Page<EcardBusinessCard> pageList = this.listPage(EcardBusinessCard.class,page,c);
        if(CollectionUtils.isEmpty(pageList.getContent())){
            return pageList;
        }
        Map<String,String> companyMap = getCompanyMap();
        for(EcardBusinessCard card:pageList.getContent()){
            card.setCompanyName(companyMap.get(card.getCompanyId()));
        }
        return pageList;
    }

    private Map<String,String> getCompanyMap(){
        List<EcardCompany> companyList = JpaUtil.linq(EcardCompany.class).list();
        if(CollectionUtils.isEmpty(companyList)){
            return new HashMap<>();
        }
        return companyList.stream().collect(Collectors.toMap(EcardCompany::getId,EcardCompany::getCompanyName));
    }

}
